<?php

namespace app\common\job;

use app\common\service\SettleConsultingServer;
use app\common\traits\JobRetryTraits;
use think\facade\Log;
use think\queue\Job;

/**
 * 补贴分账结算
 * Class TradeSettle
 * @package app\common\job
 */
class SubsidySettle
{
    use JobRetryTraits;

    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        $id = $data['id'] ?? null;

        try {

            // 补贴结算
            $result = $this->getSettleConsultingServer()->settleSubsidy($id);

            // 没有成功就重试
            if (!$result) {
                $this->retryUntilMaxAttempts($job, 24, fn($attempts) => min($attempts, 3) * 3600, '消费队列：补贴结算重试次数达到最大，ID=' . $id);
                return;
            }
        } catch (\Exception $exception) {

            Log::error('消费队列：' . $exception->getMessage());
        }

        $job->delete();
    }

    private function getSettleConsultingServer(): SettleConsultingServer
    {
        return app(SettleConsultingServer::class);
    }
}
